const express = require("express");
const multer = require("multer");
<<<<<<< HEAD
const fs = require("fs");
const bodyParser = require("body-parser");
=======
const fileUpload = require('express-fileupload');
const { List } = require('../model/model.js')
const { extname, resolve } = require("path");
>>>>>>> 2ea048f7903759d51e653d4b64815cf2dbf7f4bb
const path = require("path");
const cors = require("cors");
const app = express();
const uploadDir = path.join(__dirname, "uploads"); // 上传目录

// 确保上传目录存在
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

app.use(cors()); // 允许跨域请求
app.use(bodyParser.json());
app.use(express.json()); // 解析 JSON 请求体

// 检查已上传的分片
app.post("/check", (req, res) => {
  const { fileHash } = req.body;
  console.log("fileHash check",fileHash)

  const fileChunkDir = path.join(uploadDir, fileHash); // 分片存储目录
  if (!fs.existsSync(fileChunkDir)) {
    return res.json([]); // 如果目录不存在，返回空数组
  }

  // 返回已上传的分片索引
  const uploadedChunks = fs.readdirSync(fileChunkDir).map((chunk) => {
    return parseInt(chunk.split("-")[1]); // 提取分片索引
  });
  res.json(uploadedChunks);
});


// 设置 multer 中间件，用于处理文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const fileHash = req.query.fileHash; // 从查询参数获取 fileHash
    const chunkDir = path.join(uploadDir, fileHash);
    // 确保切片目录存在
    if (!fs.existsSync(chunkDir)) {
      fs.mkdirSync(chunkDir, { recursive: true });
    }
    cb(null, chunkDir);
  },
  filename: (req, file, cb) => {
    const { chunkIndex } = req.query;
    cb(null, `chunk-${chunkIndex}`);
  },
});

const upload = multer({ storage:storage });

// 上传文件分片
app.post("/upload", upload.single("chunk"), (req, res) => {
    const { fileHash } = req.body;
    res.status(200).send("分片上传成功");
});


// 合并分片
app.post("/merge", (req, res) => {
  const { fileName, fileHash, totalChunks } = req.body;
  console.log("fileName",req.body)
  const fileChunkDir = path.join(uploadDir, fileHash);
  const filePath = path.join(uploadDir, fileName);

  // 创建可写流用于最终合并文件
  const writeStream = fs.createWriteStream(filePath);

  for (let i = 0; i < totalChunks; i++) {
    const chunkPath = path.join(fileChunkDir, `chunk-${i}`);
    const data = fs.readFileSync(chunkPath); // 读取分片
    writeStream.write(data); // 写入最终文件
    // fs.unlinkSync(chunkPath); // 删除分片文件--留下来，可以看上传记录
  }

  writeStream.end(); // 关闭流
//   fs.rmdirSync(fileChunkDir); // 删除分片目录--留下来，可以看上传记录
  res.send("文件合并完成");
});